package com.iwhalecloud.bss.kite.cucc.web.service.accept.handler.module;

import java.time.LocalDate;
import java.time.temporal.TemporalAdjusters;
import java.util.*;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.iwhalecloud.bss.kite.common.constant.KeyConsts;
import com.iwhalecloud.bss.kite.common.constant.SymbolConsts;
import com.iwhalecloud.bss.kite.common.util.KiteBeanUtils;
import com.iwhalecloud.bss.kite.cucc.client.api.order.IOrderService;
import com.iwhalecloud.bss.kite.cucc.client.dto.order.OrderInfo;
import com.iwhalecloud.bss.kite.cucc.client.dto.order.OrderInfoListReq;
import com.iwhalecloud.bss.kite.cucc.client.dto.order.OrderInfoReq;
import com.iwhalecloud.bss.kite.cucc.client.dto.order.OrderListInfo;
import com.iwhalecloud.bss.kite.cucc.client.vo.scene.CuccServiceOfferTypeVO;
import com.iwhalecloud.bss.kite.cucc.client.vo.scene.CuccServiceOfferVo;
import com.iwhalecloud.bss.kite.cucc.common.constant.LocalDcPublicConsts;
import com.iwhalecloud.bss.kite.cucc.common.constant.LocalKeyConsts;
import com.iwhalecloud.bss.kite.cucc.common.constant.LocalServiceOfferConsts;
import com.iwhalecloud.bss.kite.cucc.common.util.DateUtils;
import com.iwhalecloud.bss.kite.cucc.service.util.ProdCateUtil;
import com.iwhalecloud.bss.kite.dataservice.cache.DcPublicCache;
import com.iwhalecloud.bss.kite.dataservice.entity.DcPublic;
import com.iwhalecloud.bss.kite.manager.inst.KiteAttr;
import com.ztesoft.bss.common.util.ContextUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.iwhalecloud.bss.kite.client.api.reception.IServiceOfferService;
import com.iwhalecloud.bss.kite.client.dto.DataResult;
import com.iwhalecloud.bss.kite.client.vo.scene.ModuleVO;
import com.iwhalecloud.bss.kite.client.vo.spec.ServiceOfferTypeVO;
import com.iwhalecloud.bss.kite.client.vo.spec.ServiceOfferVO;
import com.iwhalecloud.bss.kite.common.util.KiteListUtils;
import com.iwhalecloud.bss.kite.common.util.KiteObjectUtils;
import com.iwhalecloud.bss.kite.common.util.KiteStringUtils;
import com.iwhalecloud.bss.kite.cucc.client.dto.pos.KitePosUserDTO;
import com.iwhalecloud.bss.kite.cucc.client.vo.scene.SceneNewOfferSeneVO;
import com.iwhalecloud.bss.kite.cucc.client.vo.scene.ServiceOfferInfoModuleVO;
import com.iwhalecloud.bss.kite.dataservice.cache.OfferCache;
import com.iwhalecloud.bss.kite.dataservice.entity.spec.Offer;
import com.iwhalecloud.bss.kite.manager.api.IQuerySceneInstService;
import com.iwhalecloud.bss.kite.manager.inst.KiteOfferInst;
import com.iwhalecloud.bss.kite.manager.inst.KiteProdInst;
import com.iwhalecloud.bss.kite.manager.inst.KiteSceneInst;
import com.iwhalecloud.bss.kite.web.service.accept.bo.AcceptContext;
import com.iwhalecloud.bss.kite.web.service.accept.bo.SceneModule;
import com.iwhalecloud.bss.kite.web.service.accept.handler.module.AbstractModuleHandler;

/**
 * Created by huanghaosheng on 2020/9/16 12:47
 */
@Service
public class ServiceOfferInfoModuleHandler extends AbstractModuleHandler {

    @Autowired
    private IQuerySceneInstService querySceneInstService;

    @Autowired
    private IServiceOfferService serviceOfferService;

    @Autowired
    private IOrderService orderService;

    private  final static String  COMMON_REGION_ID = "10000000";

    @Override
    public List<ServiceOfferInfoModuleVO> execute(AcceptContext context, SceneModule sceneModule) {

        String sceneInstId = context.getSceneVo().getSceneInstId();
        //补充逻辑,进入预览返回录入页面，需要保存已操作列表
        List<String> serviceOfferIdList = querySceneInstService //获取页面勾选的操作类型
            .getExtParameterValue(sceneInstId, "BUSI_CHANGE_SERVICEOFFERID");

        SceneNewOfferSeneVO sceneNewOfferSeneVO = (SceneNewOfferSeneVO) context.getSceneVo();
        ServiceOfferInfoModuleVO serviceOfferInfoModule = new ServiceOfferInfoModuleVO();
        queryServiceOfferInfo(context, serviceOfferInfoModule);
        String offerId = serviceOfferInfoModule.getOfferId();
        String cateId = OfferCache.get(offerId).getCateId();
        //遍历serviceOfferTypeVO.getServiceOfferViews(),如果已经勾选的，则打上标识
        String tacheCode = this.querySceneInstService.getExtParameterValue(sceneInstId, "nodeCode");
        KiteSceneInst sceneInst = querySceneInstService.getSceneInst(sceneInstId);
        String upServiceOfferId = querySceneInstService.getExtParameterValue(sceneInstId, "upServiceOfferId");
        if((KiteStringUtils.equalsAny(cateId, ProdCateUtil.getDoubleLineCateIdForArr())||KiteStringUtils.equalsAny(cateId,ProdCateUtil.getDoubleLineOBCateIdForArr())) && KiteStringUtils.equalsAny("2826",upServiceOfferId,sceneInst.getServiceOfferId())
            &&(KiteStringUtils.equalsAny(tacheCode, "OrderSigned", "OrderResubmit")
            ||(KiteStringUtils.isEqual(sceneInst.getServiceOfferId(), LocalServiceOfferConsts.SERVICE_OFFER_FOLLOW)))){
            serviceOfferInfoModule.setIsEdit("F");
        }

        // 产品变更-签订，已勾选操作类型不可取消配置
        boolean notCancelOperateFlag = false;
        List<DcPublic> dcPublics = DcPublicCache.getByPcode("220402001", "notCancelOperateType", tacheCode);
        if(KiteListUtils.isNotEmpty(dcPublics)) {
            String provinceCode = sceneInst.getProvinceNbr();
            notCancelOperateFlag = dcPublics.stream().anyMatch(dcPublic -> {
                String[] dcPublicCateIds = Optional.ofNullable(dcPublic.getCodea()).orElse("").split(SymbolConsts.COMMA);
                String[] dcPublicProvs = Optional.ofNullable(dcPublic.getCodeb()).orElse("").split(SymbolConsts.COMMA);
                return KiteStringUtils.equalsAny(offerId, dcPublicCateIds) && (KiteStringUtils.equalsAny(provinceCode, dcPublicProvs) || KiteStringUtils.equalsAny(dcPublic.getCodeb(), "","09"));
            });
        }

        String oldServiceOfferIdList = querySceneInstService.getExtParameterValue(sceneInstId, "bizType");
        boolean cancelOperateFlag = !notCancelOperateFlag;

        List<CuccServiceOfferTypeVO> serviceOfferTypeVOList = serviceOfferInfoModule.getServiceOfferTypes();
        for (int i = 0; i < serviceOfferTypeVOList.size(); i++) {
            List<CuccServiceOfferVo> serviceOfferVOList = serviceOfferTypeVOList.get(i).getServiceOfferViews();
            if (KiteListUtils.isNotEmpty(serviceOfferVOList)) {
                serviceOfferVOList.stream().forEach(serviceOfferViews -> {
                    if (KiteListUtils.isNotEmpty(serviceOfferIdList) && serviceOfferIdList
                        .contains(serviceOfferViews.getServiceOfferId())) {
                        if (KiteStringUtils.isEmpty(tacheCode) || KiteStringUtils.isEqual(tacheCode, "OrderInput") || (KiteStringUtils.isEqual(tacheCode, "OrderSigned") && cancelOperateFlag)) {
                            serviceOfferViews.setCheckedFlag("YY"); //CheckedFlag为YY，则表示已经勾选
                        } else {
                            serviceOfferViews.setCheckedFlag("TT"); //CheckedFlag为TT,代表为预览模式
                        }
                        // 如果原来录入和签订的时候没勾选的二次类业务，审核、重提界面上，允许勾选，并且本次勾选允许取消
                        if (KiteStringUtils.isNotEmpty(oldServiceOfferIdList)) {
                            if (!oldServiceOfferIdList.contains(serviceOfferViews.getServiceOfferId())
                                && KiteStringUtils.equalsAny(tacheCode, "OrderAudit", "OrderResubmit", "OrderServiceOpen", "OrderSigned")) {
                                serviceOfferViews.setCheckedFlag("YY"); //operateType为YY，则表示已经勾选
                            }
                        }
                    }

                    List<DcPublic> dcPublic = DcPublicCache.get("20220113001");
                    if(KiteListUtils.isNotEmpty(dcPublic)){
                        dcPublic.stream().forEach(dc->{
                            if(KiteStringUtils.equals(cateId,dc.getPkey())&&KiteStringUtils.equals(serviceOfferViews.getServiceOfferId(),dc.getPcode())
                                &&KiteStringUtils.equals("A",dc.getCodeb())){//依赖
                                serviceOfferViews.setRelyon(dc.getCodea());
                            }else if(KiteStringUtils.equals(cateId,dc.getPkey())&&KiteStringUtils.equals(serviceOfferViews.getServiceOfferId(),dc.getPcode())
                                &&KiteStringUtils.equals("B",dc.getCodeb())){//被依赖
                                serviceOfferViews.setQuiltRelyon(dc.getCodea());
                            }
                        });
                    }
                });

                filterServiceTypeByProperty(serviceOfferVOList,sceneInstId);
                // 某些操作类型只允许在某些省份进行展示
                filterServiceOfferType(serviceOfferVOList,sceneInstId);
            }
        }
        sceneNewOfferSeneVO.setServiceOfferInfoModuleVO(serviceOfferInfoModule);
        return Collections.singletonList(serviceOfferInfoModule);
    }


    private void filterServiceTypeByProperty(List<CuccServiceOfferVo> serviceOfferTypeVOList, String sceneInstId){
        //STYPE PKEY商品分类 PCODE商品sku PNAME服务提供 COMMENTS 是否生效 CODEA 属性值json
        List<KiteProdInst> kiteProdInsts = querySceneInstService.listProdInsts(sceneInstId);
        if (kiteProdInsts != null && kiteProdInsts.size() > 0) {
            KiteOfferInst kiteOfferInst = querySceneInstService.getMainOfferInst(sceneInstId);
            String objId = kiteOfferInst.getAttrValue("cateId");
            String offerId =kiteOfferInst.getOfferId();
            List<DcPublic> dcPublicList = DcPublicCache.getByPkey("20210903001",objId);
            if(KiteListUtils.isNotEmpty(dcPublicList)){
                serviceOfferTypeVOList.removeIf(serviceOfferVO -> {
                    for (DcPublic dcPublic : dcPublicList) {
                        boolean flag = KiteStringUtils.equals(serviceOfferVO.getServiceOfferId(),dcPublic.getPname());
                        boolean if_T = KiteStringUtils.equals("T",dcPublic.getComments());
                        if((KiteStringUtils.isEmpty(dcPublic.getPcode()) || KiteStringUtils.equals(dcPublic.getPcode(),offerId))&& flag && if_T){
                            JSONObject jo = JSON.parseObject(dcPublic.getCodea());
                            for (JSONObject.Entry<String, Object> cfen : jo.entrySet()) {
                                String[] cfenVal = JSON.parseArray(cfen.getValue().toString()).toArray(new String[]{});
                                if (KiteStringUtils.equalsAny(kiteProdInsts.get(0).getAttrValue(cfen.getKey()), cfenVal)) {
                                    return false;
                                }
                            }
                        }
                    }
                    return true;
                });
            }
        }
    }

    private void filterServiceOfferType(List<CuccServiceOfferVo> serviceOfferTypeVOList, String sceneInstId) {
        KiteSceneInst sceneInst = querySceneInstService.getSceneInst(sceneInstId);
        String provinceCode = sceneInst.getProvinceNbr();
        serviceOfferTypeVOList.removeIf(serviceOfferTypeVO -> {
            List<DcPublic> dcPublicList = DcPublicCache.getByPcode("20210527001", "OperTypeProvSupport", serviceOfferTypeVO.getServiceOfferId());
            if (KiteListUtils.isNotEmpty(dcPublicList)) {
                boolean isShow = true;
                for (DcPublic dcPublic : dcPublicList) {
                    if (KiteStringUtils.isEqual(dcPublic.getCodea(), provinceCode)) {
                        isShow = false;
                    }
                }
                return isShow;
            }
            return false;
        });
    }

    private void queryServiceOfferInfo(AcceptContext context, ServiceOfferInfoModuleVO serviceOfferInfoModule) {
        String custId = context.getAcceptRequest().getCustId();
        String sceneInstId = context.getAcceptRequest().getSceneInstId();
        KiteSceneInst sceneInst = querySceneInstService.getSceneInst(sceneInstId);
        KiteOfferInst offerInst = querySceneInstService.getOfferInst(custId, sceneInst.getRootInstId());
        String serviceOfferId = sceneInst.getServiceOfferId();
        if (LocalServiceOfferConsts.SERVICE_OFFER_FOLLOW.equals(serviceOfferId)) {
            String upServiceOfferId = querySceneInstService.getExtParameterValue(sceneInstId, "upServiceOfferId");
            if (KiteStringUtils.isNotEmpty(upServiceOfferId)) {
                serviceOfferId = upServiceOfferId;
            }
        }
        String categoryId = Optional.ofNullable(OfferCache.get(offerInst.getOfferId())).map(Offer::getCateId).orElse("");
        boolean grouping = this.serviceOfferViewsGrouping(context, categoryId);

        serviceOfferInfoModule.setOfferId(offerInst.getOfferId());
        List<KiteProdInst> prodInstsFromMain = querySceneInstService.listProdInstsFromOfferInst(custId, offerInst.getOfferInstId());
        if (KiteListUtils.isNotEmpty(prodInstsFromMain)) {
            serviceOfferInfoModule.setProductId(prodInstsFromMain.get(0).getProdId());
        }
        List<KitePosUserDTO> userInfos = querySceneInstService.getExtParameterValue(sceneInstId, "serialNumber");
        if (KiteListUtils.isNotEmpty(userInfos)) {
            serviceOfferInfoModule.setAccNum(userInfos.get(0).getSerialNumber());
        }

        List<CuccServiceOfferTypeVO> cuccServiceOfferTypeVOS = new ArrayList<>();
        DataResult<List<ServiceOfferTypeVO>> serviceOfferTypeVOList = serviceOfferService.listServiceOffersByUpserviceOfferId(categoryId, serviceOfferId);
        if (KiteListUtils.isEmpty(serviceOfferTypeVOList.getResultObject())) {
            serviceOfferTypeVOList = serviceOfferService.listServiceOffersByUpserviceOfferId(offerInst.getOfferId(), serviceOfferId);
        }
        if (Objects.nonNull(serviceOfferTypeVOList) && KiteListUtils.isNotEmpty(serviceOfferTypeVOList.getResultObject())) {
            List<ServiceOfferTypeVO> serviceOfferTypeList = serviceOfferTypeVOList.getResultObject();

            // 操作类型需要支持对省份的个性化配置
            String provinceCode = ContextUtil.getLoginInfo().getUserInfo().getPostProvinceNbr();
            for (ServiceOfferTypeVO serviceOfferTypeVO : serviceOfferTypeList) {
                List<ServiceOfferVO> ServiceOfferList = serviceOfferTypeVO.getServiceOfferViews();
                ServiceOfferList.removeIf(serviceOfferVO -> !KiteStringUtils.equalsAny(serviceOfferVO.getApplyRegionId(), COMMON_REGION_ID, provinceCode));
            }
            if (grouping) {
                List<DcPublic> cfgs = DcPublicCache.get(LocalDcPublicConsts.GROUP_TIPS);
                DcPublic edits = DcPublicCache.get(LocalDcPublicConsts.SERVICE_OFFER_EDIT,categoryId);
                serviceOfferTypeList.forEach(serviceOfferType -> {
                    CuccServiceOfferTypeVO vo = new CuccServiceOfferTypeVO();
                    KiteBeanUtils.copyProperties(serviceOfferType, vo, "serviceOfferViews");
                    List<ServiceOfferVO> serviceOfferViews = serviceOfferType.getServiceOfferViews();
                    List<CuccServiceOfferVo> serviceOfferVos = KiteBeanUtils.copyPropsForList(serviceOfferViews, CuccServiceOfferVo.class);

                    // 是否五大双线代收费或落地管理产品，是：产品变更仅能资费变更
                    List<DcPublic> list = DcPublicCache.get("20210719001");
                    boolean flag = (list != null) && list.stream().anyMatch(dcPublic -> KiteStringUtils.isEqual(offerInst.getOfferId(), dcPublic.getCodeb()));
                    if(flag) {
                        serviceOfferVos.removeIf(serviceOfferVO -> !KiteStringUtils.isEqual(serviceOfferVO.getServiceOfferId(), "1009"));
                    }

                    // 互联网普通专线  山东  不展示操作类型  网站或APP服务开通/关闭
                    if(LocalKeyConsts.PROVINCE_SHANDONG.equals(sceneInst.getProvinceNbr()) && "10002224".equals(offerInst.getOfferId())) {
                        serviceOfferVos.removeIf(serviceOfferVO -> KiteStringUtils.isEqual(serviceOfferVO.getServiceOfferId(), "2034"));
                    }

                    for (int i = 0; i < serviceOfferVos.size(); i++) {
                        CuccServiceOfferVo serviceOfferVo = serviceOfferVos.get(i);
                        String alert = cfgs.stream().filter(cfg -> serviceOfferVo.getServiceOfferId().equals(cfg.getPcode())).findFirst()
                            .map(DcPublic::getCodea).orElse("");
                        if (KiteStringUtils.isNotEmpty(alert)) {
                            serviceOfferVo.setRemark(alert);
                        }

                        // 仅 互联网普通专线，IP地址变更  名称修改为  IP参数变更（2022-04-07版本需求，延期至2022-05-10上线）
                        /*if("2004029".equals(categoryId) && "1022".equals(serviceOfferVo.getServiceOfferId())) {
                            serviceOfferVo.setName("IP参数变更");
                        }*/

                        // 根据省份个性化处理，变更是否可编辑，例：福建省互联网专线产品变更不可选择接入变更
                        if(null!=edits&&edits.getCodea().equals(sceneInst.getProvinceNbr())&&edits.getCodeb().equals(serviceOfferVo.getServiceOfferId())){
                            serviceOfferVo.setIsEdit(KeyConsts.IFTRUE_F);
                        }
                    }
                    vo.setServiceOfferViews(serviceOfferVos);
                    cuccServiceOfferTypeVOS.add(vo);
                });
            }
            else {
                CuccServiceOfferTypeVO vo = new CuccServiceOfferTypeVO();
                List<ServiceOfferVO> serviceOfferViews = new ArrayList<>();
                serviceOfferTypeList.forEach(serviceOfferType -> {
                    if (!KiteObjectUtils.isEmpty(serviceOfferType) && KiteListUtils
                        .isNotEmpty(serviceOfferType.getServiceOfferViews())) {
                        serviceOfferViews.addAll(serviceOfferType.getServiceOfferViews());
                    }
                });
                List<CuccServiceOfferVo> serviceOfferVo = KiteBeanUtils.copyPropsForList(serviceOfferViews, CuccServiceOfferVo.class);

                // SDWAN产品变更子操作类型是否可编辑
                List<String> notEditServiceOfferIds = this.sdwanNotEditServiceOfferIds(serviceOfferInfoModule, sceneInstId);
                if(KiteListUtils.isNotEmpty(notEditServiceOfferIds)) {
                    serviceOfferVo.forEach(serviceOffer -> {
                        if(notEditServiceOfferIds.contains(serviceOffer.getServiceOfferId())) {
                            serviceOffer.setIsEdit(KeyConsts.IFTRUE_F);
                        }
                    });
                }
                vo.setServiceOfferViews(serviceOfferVo);
                cuccServiceOfferTypeVOS.add(vo);
            }
        }

        if (grouping) {
            serviceOfferInfoModule.setGrouping("T");
        }
        serviceOfferInfoModule.setServiceOfferTypes(cuccServiceOfferTypeVOS);
    }

    @Override
    public List<ModuleVO> previewSceneVo(AcceptContext context, SceneModule sceneModule) {
        SceneNewOfferSeneVO sceneNewOfferSeneVO = (SceneNewOfferSeneVO) context.getSceneVo();
        ServiceOfferInfoModuleVO serviceOfferInfoModule = new ServiceOfferInfoModuleVO();
        queryServiceOfferInfo(context, serviceOfferInfoModule);
        List<String> serviceOfferIdList = querySceneInstService //获取页面勾选的操作类型
            .getExtParameterValue(context.getSceneVo().getSceneInstId(), "BUSI_CHANGE_SERVICEOFFERID");
        List<CuccServiceOfferTypeVO> serviceOfferTypeVOList = serviceOfferInfoModule.getServiceOfferTypes();
        for (int i = 0; i < serviceOfferTypeVOList.size(); i++) {
            List<CuccServiceOfferVo> serviceOfferVOList = serviceOfferTypeVOList.get(i).getServiceOfferViews();
            if (KiteListUtils.isNotEmpty(serviceOfferIdList)) {
                serviceOfferIdList.stream().forEach(serviceOfferId -> {
                    for (CuccServiceOfferVo serviceOfferVO : serviceOfferVOList) {
                        if (serviceOfferId.equals(serviceOfferVO.getServiceOfferId())) {
                            serviceOfferVO.setCheckedFlag("TT"); //CheckedFlag为TT,代表为预览模式
                        }
                    }
                });
            }
        }
        serviceOfferInfoModule.setIsEdit("F");
        sceneNewOfferSeneVO.setServiceOfferInfoModuleVO(serviceOfferInfoModule);
        return Collections.singletonList(serviceOfferInfoModule);
    }

    /**
     * SDWAN产品变更子操作类型，判断是否可编辑
     * @author zhang.song
     * @date 2022-03-16 11:21
     * @param serviceOfferInfoModule
     * @param sceneInstId
     * @return java.util.List<java.lang.String>
     */
    private List<String> sdwanNotEditServiceOfferIds(ServiceOfferInfoModuleVO serviceOfferInfoModule, String sceneInstId) {
        List<String> notEditServiceOfferIds = new ArrayList<>();
        if (KiteStringUtils.equals(serviceOfferInfoModule.getOfferId(), "10003406")) {
            // SDWAN，判断当期是否弹性升速期内，禁选  升降速、弹性升速，否则  禁选  取消弹性升速
            List<KiteProdInst> kiteProdInsts = querySceneInstService.listProdInsts(sceneInstId);
            if (kiteProdInsts != null && kiteProdInsts.size() > 0) {
                KiteAttr elasticStartAttr = kiteProdInsts.get(0).getAttr("200002715");
                KiteAttr elasticEndAttr = kiteProdInsts.get(0).getAttr("200002140");
                String elasticStartDate = elasticStartAttr == null ? null : elasticStartAttr.getOldValue();
                String elasticEndDate = elasticEndAttr == null ? null : elasticEndAttr.getOldValue();
                boolean isElasticFlag = DateUtils.compareDate(elasticStartDate, elasticEndDate);

                if (isElasticFlag) {
                    notEditServiceOfferIds.add("1011");
                    notEditServiceOfferIds.add("1051");
                } else {
                    notEditServiceOfferIds.add("1052");
                }
            }

            if (!notEditServiceOfferIds.contains("1051")) {
                // SDWAN 弹性升速 订单当月已有三次，则禁选
                String serialNumber = serviceOfferInfoModule.getAccNum();
                if (this.sdwanElasticOperateValid(sceneInstId, serialNumber)) {
                    notEditServiceOfferIds.add("1051");
                }
            }
        }
        return notEditServiceOfferIds;
    }

    /**
     * SDWAN 判断本月 弹性升速 操作次数是否 >=3，是，则禁选 弹性升速
     *
     * @param sceneInstId
     * @param serialNumber
     * @return boolean 本月 弹性升速 操作次数 >=3
     * @author zhang.song
     * @date 2021-04-21 17:25
     */
    private boolean sdwanElasticOperateValid(String sceneInstId, String serialNumber) {
        if (KiteStringUtils.isEmpty(serialNumber)) {
            return false;
        }

        OrderInfoListReq orderInfoListReq = new OrderInfoListReq();
        orderInfoListReq.setQueryType("order");
        orderInfoListReq.setPage("1");
        orderInfoListReq.setSize("20");
        OrderInfoReq order = new OrderInfoReq();
        order.setSerialNumber(serialNumber);
        order.setBizType("1051");
        order.setOrderId(querySceneInstService.getExtParameterValue(sceneInstId, "outOrderId"));
        // 设置查询申请时间范围，本月第一天到最后一天
        LocalDate nowDate = LocalDate.now();
        LocalDate firstday = nowDate.with(TemporalAdjusters.firstDayOfMonth());
        LocalDate lastDay = nowDate.with(TemporalAdjusters.lastDayOfMonth());
        order.setStartTime(firstday.toString());
        order.setFinishTime(lastDay.toString());
        orderInfoListReq.setOrder(order);

        OrderListInfo orderListInfo = orderService.queryOrderList(orderInfoListReq);
        if (orderListInfo == null || !KiteStringUtils.equals(orderListInfo.getCode(), "00000")) {
            return false;
        }
        List<OrderInfo> orderInfoList = orderListInfo.getOrderInfoList();
        int count = 0;
        if (orderInfoList != null && orderInfoList.size() > 2) {
            for (OrderInfo orderInfo : orderInfoList) {
                // 排序失败的订单状态（4：订单取消；7：订单异常；8：集客退单）
                if (!KiteStringUtils.equalsAny(orderInfo.getStatus(), "4", "7", "8")) {
                    count++;
                }
            }
        }
        return (count > 2);
    }

    private boolean serviceOfferViewsGrouping(AcceptContext context, String cateId) {
        return KiteStringUtils.equalsAny(cateId, ProdCateUtil.getDoubleLineCateIdForArr());
    }
}
